package com.dianqu.weather.web.engine.strategy;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import com.dianqu.weather.core.model.WeatherInfo;
import com.dianqu.weather.core.model.WeatherInfo.DetailInfo;
import com.dianqu.weather.web.engine.EngineStrategyAbstract;

public class BaiduStrategy extends EngineStrategyAbstract {

	private final Logger logger = Logger.getLogger(getClass());
	private static final String WEB_URL = "http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=n5RiXGGwhF61EajoGGeD5ttr";

	protected WeatherInfo format(String resource) {
		if (!resource.trim().startsWith("{"))
			return null;
		JSONObject json = JSONObject.fromObject(resource);
		int error = json.getInt("error");
		if (error == 0) {
			WeatherInfo weather = new WeatherInfo();
			weather.setCurrentDate(new Date());
			JSONArray result = json.getJSONArray("results");
			JSONObject ob = result.getJSONObject(0);
			weather.setCityname(ob.getString("currentCity"));
			weather.setPm25(ob.getString("pm25"));
			JSONArray weatherData = ob.getJSONArray("weather_data");
			List<DetailInfo> infos = new ArrayList<DetailInfo>();
			for (int i = 0; i < weatherData.size(); i++) {
				JSONObject object = weatherData.getJSONObject(i);
				DetailInfo info = new DetailInfo();
				info.setDatetime(object.getString("date"));
				info.setTemperature(object.getString("temperature"));
				info.setWeather(object.getString("weather"));
				info.setWind(object.getString("wind"));
				infos.add(info);
			}
			weather.setInfos(infos);
			return weather;
		}
		return null;
	}

	protected String getResource(String location) {
		logger.info("Searching " + location + " from baidu.");
		String url = String.format(WEB_URL, location);
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		InputStream is = null;
		try {
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				is = response.getEntity().getContent();
				return IOUtils.toString(is, "utf-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
			get.releaseConnection();
			client.getConnectionManager().shutdown();
		}
		return null;
	}

}
